//工具函数库，仔仔编写。

let _tool = {
	//搜索结果
	async search(html) {
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		var booklist = [];
		var data = $('.block');
		data.each(function(i, el) {
			booklist.push({
				id: $(this).find('.block_img').eq(0).find('a').attr('href'),
				img: $(this).find('.block_img').eq(0).find('img').attr('src'),
				name: $(this).find('.block_txt').eq(0).find("h2").text(),
				author: $(this).find('.block_txt').eq(0).find("p").eq(2).text().myReplace('作者：',''),
				type: $(this).find('.block_txt').eq(0).find("p").eq(1).text().myReplace('分类：',''),
				// sort: '未知',
				news:  $(this).find('.block_txt').eq(0).find("p").eq(3).text().myReplace('最新章节：',''),
				// newsTime: $(this).find(".odd").eq(1).text(),
				// introduce: $(this).find('.bookinfo').find('.intro_line').text().myReplace(' ', '')
			})
		});
		return booklist;
	},
	//完本小说
	async searchEndBooks(html) {
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		var booklist = [];
		var data = $('ul');
		data.each(function(i, el) {
			var id = $(this).find('.tjimg').eq(0).find('a').attr('href');
			if(!id){
				return;
			}
			booklist.push({
				id: $(this).find('.tjimg').eq(0).find('a').attr('href'),
				img: $(this).find('.tjimg').eq(0).find('img').attr('src'),
				name: $(this).find('.tjxs').eq(0).find("span").eq(0).text(),
				author: $(this).find('.tjxs').eq(0).find("span").eq(1).text().myReplace('作者：',''),
				// type: $(this).find('.block_txt').eq(0).find("p").eq(1).text().myReplace('分类：',''),
				// sort: '未知',
				// news:  $(this).find('.block_txt').eq(0).find("p").eq(3).text().myReplace('最新章节：',''),
				// newsTime: $(this).find(".odd").eq(1).text(),
				overTime: $(this).find('.tjxs').eq(0).find("span").eq(3).text().myReplace(' ', ''),
				introduce: $(this).find('.tjxs').eq(0).find("span").eq(2).text().myReplace(' ', '')
			})
		});
		return booklist;
	},
	// 排行榜
	async searchRankingList(html, period) {
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		var booklist = [];
		var data = $('ul.xbk');

		data.each(function(i, el) {
			booklist.push({
				id: $(this).find('.tjimg').find('a').attr('href').myReplace('/', ''),
				img: $(this).find('.tjimg').find('img').attr('src'),
				name: $(this).find('.tjxs').find('span').eq(0).find('a').text(),
				author: $(this).find('.tjxs').find('span').eq(1).text().myReplace(' ', '').myReplace('作者：',''),
				hot: $(this).find('.tjxs').find('span').eq(3).find('i').text(),
				introduce: $(this).find('.tjxs').find('span').eq(2).text().myReplace(' ', '')
			})
		});
		return booklist;
	},
	//详情数据
	async DetailsData(html,id, source) {
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		// 详情数据
		let DetailsArr = {};
		var img,name,author,type,intro,state,updateTime,news;
		// 不同源的数据抓取
		if(source === "https://m.xbiquwx.la/"){
			img = $('.block_img2').eq(0).find('img').attr('src');
			name = $('.block_txt2').eq(0).find('h2').text();
			author = $('.block_txt2').eq(0).find('p').eq(1).text().myReplace('作者：','');
			type = $('.block_txt2').eq(0).find('p').eq(2).text().myReplace('分类：','');
			state = $('.block_txt2').eq(0).find('p').eq(3).text().myReplace('状态：','');
			intro = $('.intro_info').eq(0).text();
			intro = intro.substring(0,intro.indexOf('最新章节推荐地址'));
			updateTime = $('.block_txt2').eq(0).find('p').eq(4).text().myReplace('更新：','');
			news = $('.block_txt2').eq(0).find('p').eq(5).find('a').text();
		}else if(source === "https://wap.xbiquge.la/"){
			img = $('.block_img2').eq(0).find('img').attr('src');
			name = $('.block_txt2').eq(0).find('h2').text();
			author = $('.block_txt2').eq(0).find('p').eq(1).text().myReplace('作者：','');
			type = $('.block_txt2').eq(0).find('p').eq(2).text().myReplace('分类：','');
			state = $('.block_txt2').eq(0).find('p').eq(3).text().myReplace('状态：','');
			intro = $('.intro_info').eq(0).text();
			intro = intro.substring(0,intro.indexOf('最新章节推荐地址'));
			updateTime = $('.block_txt2').eq(0).find('p').eq(4).text().myReplace('更新：','');
			news = $('.block_txt2').eq(0).find('p').eq(5).find('a').text();
		}
		DetailsArr.data = {img: img, name: name, author: author, type: type, intro: intro, state: state, updateTime: updateTime, news: news,}
		// 抓取章节列表所在的li集合
		let liArr = $('.cover ul').eq(1).find('li');
		// $('#list').find('dd');
		// let s = $('.cover').find('ul li');
		// debugger;
		// s.each(function(i, elem) {
		// 	console.log("id"+ $(this).find('a').text())
		// 	});
		// 抓取章节列表
		let NewArr = [];
		if(source=="https://m.xbiquwx.la/"){
			liArr.each(function(i, elem) {
				NewArr.push({
					id: $(this).find('a').attr('href'),
					name: $(this).find('a').text(),
					url: $(this).find('a').attr('href')
				})
			});
		}else if(source==2){
			liArr.each(function(i, elem) {
				NewArr.push({
					id: '/'+id+'/'+$(this).find('a').attr('href'),
					name: $(this).find('a').text(),
					url: '/'+id+'/'+$(this).find('a').attr('href')
				})
			});
		}
		// 去重
		var result = [];
		var obj = {};
		// 通过章节的url去重
		for (var i = NewArr.length - 1; i >= 0; i--) {
			if (!obj[NewArr[i].url]) {
				result.push(NewArr[i]);
				obj[NewArr[i].url] = true;
			}
		}
		DetailsArr.list = result.reverse();
		return DetailsArr;
	},
    // 章节
	async ChapterData(html,id, source) {
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		var newoptionArr = [];
		let optionArr = $('.listpage').find('option');
		optionArr.each(function(i, elem) {
			newoptionArr.push({
				url: $(this).val(),
				name: $(this).text()
				});
			});
		return newoptionArr;
	},
	// // 章节
	// async ChapterData(html,id, source) {
	// 	var this_ = this;
	// 	const cheerio = require('cheerio');
	// 	const $ = cheerio.load(html, {
	// 		_useHtmlParser2: true
	// 	});
	// 	var newoptionArr = [];
	// 	let optionArr = $('.listpage').find('option');
	//
	// 	optionArr.each(function(i, elem) {
	// 		newoptionArr.push({
	// 			url: $(this).val(),
	// 			name: $(this).text()
	// 			});
	// 		});
	//
	// 	return newoptionArr;
	// },
	// 章节2
	async ChapterData2(html,id, source) {
		let DetailsArr = {};
		var this_ = this;
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		var newoptionArr = [];
		let optionArr = $('#list').find('dd');
		optionArr.each(function(i, elem) {
			newoptionArr.push({
				id: '/'+id+'/' + $(this).find('a').attr('href'),
				name: $(this).find('a').text(),
				url: '/'+id+'/' + $(this).find('a').attr('href')
			})
		});
		// 去重
		var result = [];
		var obj = {};
		// 通过章节的url去重
		for (var i = newoptionArr.length - 1; i >= 0; i--) {
			if (!obj[newoptionArr[i].url]) {
				result.push(newoptionArr[i]);
				obj[newoptionArr[i].url] = true;
			}
		}
		DetailsArr.list = result.reverse();
		return DetailsArr;
	},
	
	GetBookInfo(html) {
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		let img = '/api' + $('#fmimg').find('img').attr('src');
		let name = $('#info').find('h1').text();
		let author = $('#info').find('p').eq(0).text();
		let intro = $('#intro').text();

		let book = {
			img: img,
			name: name,
			author: author,
			intro: intro
		};
		return book;
	},
	//获取书籍内容
	async GetReadContentData(html) {
		const cheerio = require('cheerio');
		const $ = cheerio.load(html, {
			_useHtmlParser2: true
		});
		let Content = $('#content').html().replace('&#x5929;&#x624D;&#x4E00;&#x79D2;&#x8BB0;&#x4F4F;&#x3010;&#x7231;&#x5C1A;&#x5C0F;&#x8BF4;&#x7F51;biquge.info&#x3011;&#x4E3A;&#x60A8;&#x63D0;&#x4F9B;&#x7CBE;&#x5F69;&#x5C0F;&#x8BF4;&#x9605;&#x8BFB;&#x3002;','');
		return Content;
	},
	//获取书架数据
	async GetBookListData() {
		try {
			const value = uni.getStorageSync('bookshelf_list');
			if (value) {
				return value;
			}
		} catch (e) {
			return '';
		}
	},
	//加入到书架
	async AddBookListData(data) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			let newArr = [];
			newArr.push(data);
			await this.AddBookListStorage(newArr);
		} else {
			let BookID = await this.GetBookListID(data.id);
			if (BookID == false) {
				BookList.push(data);
				await this.AddBookListStorage(BookList);
			}
		}
	},
	//更新书架信息
	async UpBookListData(data) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			console.log('书架没有内容');
		} else {
			let BookID = false;
			for (let i = 0; i < BookList.length; i++) {
				if (BookList[i].id == data.id) {
					BookList[i].news = data.news;
					BookList[i].page = data.page;
					BookList[i].index = data.index;
					BookList[i].name = data.name;
					BookID = true;
				}
			}
			if (BookID) {
				await this.AddBookListStorage(BookList);
			}
		}
	},
	//加入到书架数据
	async AddBookListStorage(data) {
		try {
			uni.setStorageSync('bookshelf_list', data);
		} catch (e) {
			// error
		}
	},
	//书架中是否已经存在
	async GetBookListID(BookID) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			return false;
		} else {
			let state = false;
			for (let i = 0; i < BookList.length; i++) {
				if (BookList[i].id == BookID) {
					state = true;
				}
			}
			return state;
		}
	},
	//删除书籍
	async DelBookList(BookID) {
		let BookList = await this.GetBookListData();
		if (BookList == "" || BookList == null || BookList == undefined) {
			return false;
		} else {
			let newArr = [];
			for (let i = 0; i < BookList.length; i++) {
				if (BookID.includes(BookList[i].id) == false) {
					newArr.push(BookList[i]);
				}
			}
			await this.AddBookListStorage(newArr);
		}
	},
	//清理缓存
	async clearStorage() {
		try {
			uni.setStorageSync('bookshelf_list', '');
			uni.clearStorageSync();
		} catch (e) {
			// error
		}
	},
	//截取指定字符串
	async GetInterceptTheSpecifiedString(str, firstStr, secondStr) {
		if (str == "" || str == null || str == undefined) { // "",null,undefined
			return "";
		}
		if (str.indexOf(firstStr) < 0) {
			return "";
		}
		var subFirstStr = str.substring(str.indexOf(firstStr) + firstStr.length, str.length);
		var subSecondStr = subFirstStr.substring(0, subFirstStr.indexOf(secondStr));
		return subSecondStr;
	},
	//获取字符串的真实长度（字节长度）
	strLeng(str) {
		if (str) {
			let len = str.length,
				truelen = 0;
			for (let x = 0; x < len; x++) {
				if (str.charCodeAt(x) > 128) {
					truelen += 2;
				} else {
					truelen += 1;
				}
			}
			return truelen;
		} else {
			return 0;
		}
	}



};

export default _tool;
